#include"preCmpH.h"
#include"UIControlContainer.h"

BEGIN_NAMESPACE(ui_manager)
BEGIN_NAMESPACE(ui_controls)
//=====================================
// Constructors, Destructor, Operators
//=====================================

UIControlContainer::UIControlContainer()
: children_()
{
}
UIControlContainer::~UIControlContainer()
{
	Clear();
}
//=====================================
// Functionality
//=====================================

void UIControlContainer::AddChild( UIControl* child )
{
	children_.push_front(child);
	child->setParent(*this);
}

void UIControlContainer::RemoveChild(std::string child_name)
{
	std::list<ui_controls::UIControl*>::iterator it;
	for( it = children_.begin(); it != children_.end(); it++){
		if( (*it)->getName() == child_name){
			delete *it;
			children_.erase(it);
		}
	}
}
void UIControlContainer::PostEvent(ui_events::UIEvent uievent)
{
	HandleEvent(uievent);
	if(!children_.empty()){
		std::list<ui_controls::UIControl*>::iterator it;
		for( it = children_.begin(); it != children_.end(); it++){
			if(uievent.getMsgFlag() == ui_events::UIEvent::FLAG_RENDER){
				UIPoint temp = uievent.getRenderParentPosition();
				uievent.setRenderMsg(temp.getX() + pos_.getX(), temp.getY() + pos_.getY(), true);
				(*it)->HandleEvent(uievent);

			} else if(uievent.getMsgFlag() == ui_events::UIEvent::FLAG_MOUSE){
				UIPoint temp1 = uievent.getMousePosition(true);
				temp1.setX( temp1.getX() - pos_.getX() );
				temp1.setY( temp1.getY() - pos_.getY() );
				UIPoint temp2 = uievent.getMousePosition(false);
				ushort f = uievent.getMouseButtonState();
				ushort b = uievent.getMouseButton();
				uievent.setMouseMsg(temp2.getX(),temp2.getY(),temp1.getX(),temp1.getY(),f,b);
				(*it)->HandleEvent(uievent);

			} else if(uievent.getMsgFlag() == ui_events::UIEvent::FLAG_TICK){
				(*it)->HandleEvent(uievent);

			} else if(uievent.getMsgFlag() == ui_events::UIEvent::FLAG_KEYBOARD){
				(*it)->HandleEvent(uievent);
			}
			
		}
	}
}
void UIControlContainer::Clear()
{
	std::list<ui_controls::UIControl*>::iterator it;
	for( it = children_.begin(); it != children_.end(); it++){
			delete *it;
	}
	children_.clear();
}

UIControl* UIControlContainer::getChild( std::string child_name )
{
	std::list<ui_controls::UIControl*>::iterator it;
	for( it = children_.begin(); it != children_.end(); it++){
		if( (*it)->getName() == child_name){
			return (*it);
		}
	}
	return null;
}

END_NAMESPACE // UI controls
END_NAMESPACE // UI manager